package leetcode.f1t100;

/**
 * 罗马数字转阿拉伯数字
 * https://leetcode.com/problems/roman-to-integer/
 *
 * @author lichx
 * @date 2021/10/9 16:48
 */
public class Q13_RomanToInteger {
    public int romanToInt(String s) {
        char[] c = s.toCharArray();
        return f(c);
    }
    public static int f(char[] c){
        int ans = 0;
        int[] symbolInt = new int[]{1, 5, 10, 50, 100, 500, 1000};
        String symbol = new String("IVXLCDM");
        int l = c.length;
        if (l>15) {
            return -1;
        }
        int cur=-1,next=symbol.indexOf(c[0]),i=0;
        while(i<l){
            cur = symbol.indexOf(c[i]);
            next = i<l-1 ? symbol.indexOf(c[i+1]) : -1;

            if(cur<next){
                if((next&1)==1){
                    ans += symbolInt[next] - symbolInt[next-1];
                }else{
                    ans += symbolInt[next] - symbolInt[next-2];
                }
                i+=2;
            }else{
                ans+=symbolInt[cur];
                i++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int times = 1000;
        for(int i=0;i<times;i++){
            int num = (int)(Math.random()*3999);
            int temp = num;
            String s = Q12_IntegerToRoman.f(temp);
            int ans = f(s.toCharArray());
            if(num != ans){
                System.out.println(s);
                System.out.println(num);
                System.out.println(ans);
                System.out.println(f(s.toCharArray()));
                return;
            }
        }
        System.out.println("finish");
    }
}
